package cn.pn.project.controller;

import cn.pn.project.client.base.AddressFeign;
import cn.pn.project.common.CommunicationNumberVerification;
import cn.pn.project.common.DtoUtil;
import cn.pn.project.common.RedisUtils;
import cn.pn.project.module.base.AddressModule;
import cn.pn.project.pojo.base.Address;
import cn.pn.project.pojo.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("address")
public class AddressController {
    @Autowired
    private AddressFeign addressFeign;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 新增地址
     *
     * @param address 去掉地址id 和预留扩展列 剩下必填 存在
     * @return
     * @throws RuntimeException
     */
    @PostMapping(value = {"/v/add"})
    public Object addAddress(Address address, HttpServletRequest request) throws RuntimeException {
        if (address == null) {
            return DtoUtil.returnFail("缺少参数", "6000");
        }
        if (address.getAddressId() != null) {//主键id 为null时
            address.setAddressId(null);
        }
        User u = getUser(request);
        if (u == null || u.getUserId() == null || u.getUserId().equals(0)) {
            return DtoUtil.returnSuccess("用户未登录", "0001");
        }

       /* //必须存在用户id
        if (address.getUserId() == null || address.getUserId().equals(0))
            return DtoUtil.returnFail("缺少参数userId", "0002");*/
        //必须有收件人
        if (address.getReceiveName() == null || address.getReceiveName().length() == 0)
            return DtoUtil.returnFail("请填写收件人姓名", "0002");
        //和符合规则的手机号
        if (!CommunicationNumberVerification.isMobileNO(address.getTelephone()))
            return DtoUtil.returnFail("请填写正确的手机号", "0002");
        //和一定长度的详细地址
        if (address.getReceiveAddress() == null || address.getReceiveAddress().length() < 10)
            return DtoUtil.returnFail("请填写10个字数以上的详细地址", "0002");
        //必须有省id
        if (address.getProvinceId() == null || address.getProvinceId().equals(0))
            return DtoUtil.returnFail("请选择所在省", "0002");
        //必须有市id
        if (address.getCityId() == null || address.getCityId().equals(0))
            return DtoUtil.returnFail("请选择所在市", "0002");
        //必须有区id
        if (address.getCountyId() == null || address.getCountyId().equals(0))
            return DtoUtil.returnFail("请选择所在区", "0002");
        address.setUserId(u.getUserId());
        //查询userId 下未删除的地址不超过10个
        List<AddressModule> list = addressFeign.findAddressByUserId(address);
        if (list != null && list.size() == 10)//拥有10个地址
            return DtoUtil.returnSuccess("地址过多，每个用户最多拥有10个地址,除非拿钱买", "0002");

        if (addressFeign.addAddress(address)) {
            return DtoUtil.returnSuccess("成功添加数据");
        } else {
            return DtoUtil.returnFail("系统异常", "0002");
        }

    }

    /**
     * 修改地址 地址id userId  必须有 剩下的随便改
     *
     * @param address
     * @return
     * @throws RuntimeException
     */
    @PostMapping(value = {"/v/changeAddress", "/v/change", "/v/update"})
    public Object changeAddress(Address address, HttpServletRequest request) throws RuntimeException {
        //参数不能为空
        if (address == null)
            return DtoUtil.returnFail("缺少数据", "6000");
        //addressId不能为null
        if (address.getAddressId() == null || address.getAddressId().equals(0))
            return DtoUtil.returnFail("addressId不能为空", "6000");
        User u = getUser(request);
        if (u == null || u.getUserId() == null || u.getUserId().equals(0)) {
            return DtoUtil.returnSuccess("用户未登录", "0001");
        }
        /*  //userId不能为null
        if (address.getUserId() == null || address.getUserId().equals(0))
            return DtoUtil.returnFail("userId不能为空", "6000");*/
        if (address.getTelephone() != null && !CommunicationNumberVerification.isMobileNO(address.getTelephone()))
            return DtoUtil.returnFail("请输入正确的电话号码", "6000");
        //判断这个地址属于该用户
        Address address1 = new Address();
        address1.setUserId(address.getUserId());
        List<AddressModule> addressModuleList = addressFeign.findAddressByUserId(address1);
        if (addressModuleList == null || addressModuleList.size() == 0)//查询出空数据 不属于该用户的地址
            return DtoUtil.returnFail("提供数据异常", "0002");
        for (int i = 0; i < addressModuleList.size(); i++) {
            if (addressModuleList.get(i).getAddressId().equals(address.getAddressId())) {//属于该用户
                //数据修复
                addressModuleList.get(i).setReceiveName((address.getReceiveName() == null || address.getReceiveName().length() < 0) ? addressModuleList.get(i).getReceiveName() : address.getReceiveName());
                addressModuleList.get(i).setReceiveAddress((address.getReceiveAddress() == null || address.getReceiveAddress().length() < 10) ? addressModuleList.get(i).getReceiveAddress() : address.getReceiveAddress());
                addressModuleList.get(i).setTelephone((address.getTelephone() == null || !CommunicationNumberVerification.isMobileNO(address.getTelephone())) ? addressModuleList.get(i).getTelephone() : address.getTelephone());
                addressModuleList.get(i).setProvinceId((address.getProvinceId() == null || address.getProvinceId().equals(0)) ? addressModuleList.get(i).getProvinceId() : address.getProvinceId());
                addressModuleList.get(i).setCityId((address.getCityId() == null || address.getCityId().equals(0)) ? addressModuleList.get(i).getCityId() : address.getCityId());
                addressModuleList.get(i).setCountyId((address.getCountyId() == null || address.getCountyId().equals(0)) ? addressModuleList.get(i).getCountyId() : address.getCountyId());
                if (addressFeign.changeAddress(addressModuleList.get(i))) {//执行修改
                    return DtoUtil.returnSuccess("成功修改指定数据");
                } else {
                    return DtoUtil.returnFail("修改失败", "0002");
                }
            } else if (i == (addressModuleList.size() - 1)) //非改用户的数据
                return DtoUtil.returnFail("提供数据异常", "0002");

        }
        return DtoUtil.returnFail("系统异常", "0002");

    }

    /**
     * 删除地址
     *
     * @param addressId 地址唯一标识
     * @return
     * @throws RuntimeException
     */
    @PostMapping(value = {"/v/removeAddress", "/v/remove", "/v/delete"})
    public Object removeAddress(@RequestParam("addressId") Integer addressId, HttpServletRequest request) throws RuntimeException {
        if (addressId == null) {
            return DtoUtil.returnFail("addressId不能为空", "6000");
        }
        User u = getUser(request);
        if (u == null || u.getUserId() == null || u.getUserId().equals(0)) {
            return DtoUtil.returnSuccess("用户未登录", "0001");
        }

       /* //addressId不能为null
        if (userId == null || userId.equals(0))
            return DtoUtil.returnFail("userId不能为空", "6000");*/

        //获取这个用户的所有地址
        Address address1 = new Address();
        address1.setUserId(u.getUserId());
        List<AddressModule> addressModuleList = addressFeign.findAddressByUserId(address1);
        if (addressModuleList == null || addressModuleList.size() == 0)//查询出空数据 不属于该用户的地址
            return DtoUtil.returnFail("提供数据异常", "0002");
        for (int i = 0; i < addressModuleList.size(); i++) {//便利地址判断是否属于该用户
            if (addressModuleList.get(i).getAddressId().equals(addressId))//属于该用户
            {
                address1.setAddressId(addressId);
                if (addressFeign.removeAddress(address1)) {

                    return DtoUtil.returnSuccess("成功删除指定数据");
                } else {
                    return DtoUtil.returnFail("删除数据失败", "0002");
                }
            } else if (i == (addressModuleList.size() - 1)) //非该用户的数据
                return DtoUtil.returnFail("提供数据异常", "0002");

        }
        return DtoUtil.returnFail("系统异常", "0002");


    }

    /**
     * 地址查询
     *
     * @param address 用户id  默认地址标识
     * @return
     * @throws RuntimeException
     */
    @PostMapping(value = {"/v/findAddressByUserId", "/v/select", "/v/findByUserId"})
    public Object findAddressByUserId(Address address, HttpServletRequest request) throws RuntimeException {
        if (address == null) {
            return DtoUtil.returnFail("参数缺失", "6000");
        }
        User u = getUser(request);
        if (u == null || u.getUserId() == null || u.getUserId().equals(0)) {
            return DtoUtil.returnSuccess("用户未登录", "0001");
        }
        /*if (address.getUserId() == null)
            return DtoUtil.returnFail("userId不能为空", "6000");
*/      address.setUserId(u.getUserId());
        Object o = addressFeign.findAddressByUserId(address);
        if (o != null) {
            return DtoUtil.returnSuccess("获取地址成功",o);
        } else {
            return DtoUtil.returnFail("系统异常", "0002");

        }
    }

    /**
     * 获取当前登陆的用信息
     *
     * @param request
     * @return
     */
    public User getUser(HttpServletRequest request) {
        User u = null;
        try {
            u = (User) redisUtils.get(request.getHeader("token"));
        } catch (Exception e) {
            System.out.println("获取用户失败");
            e.printStackTrace();

        }
        return u;
    }
}
